import Request from './request'
const http = new Request()

let baseUrl = 'https://imcnpe.knew-how.com' //公共baseUrl

try {
	// if (location.hostname == 'localhost') {
	// 	baseUrl = ''
	// }
} catch (e) {

}

// request全局参数设置
http.setConfig(config => {
	/* 设置全局配置 */
	config.baseUrl = baseUrl
	config.header = { ...config.header, }
	// console.log('222')
	// console.log(config)
	return config
})

http.interceptor.request(config => {
	/* 请求之前拦截器 */
	// config.header['access_token'] = uni.getStorageSync('access_token')
	//config.header['token']= '3780ac5f-c4b3-467a-95b9-45c4fb53594f';
	//config.header['token']= '290b49f7-16b9-4ffc-b4c7-c4ecfa99f5dd'
	//config.header['shop_id']= 1;
	// config.header['shop_id'] = uni.getStorageSync('shop_id')
	// 根据custom参数中配置的是否需要token，添加对应的请求头
	const tokenStr = uni.getStorageSync('access_token')
	// console.log(tokenStr, '@')
	if (tokenStr) {
		// 可以在此通过vm引用vuex中的变量，具体值在vm.$store.state中
		config.header.Authorization = tokenStr
	}
	// console.log(config, 'config')
	return config
}, error => {
	return Promise.reject(error)
})

http.interceptor.response(async response => {
	// console.log(response, 'responseresponseresponse')
	/* 请求之后拦截器 */
	switch (response.data.code || response.data.status) {

		case 1:
			return response.data
		case 101:

			break
		case 200:
			return response.data
			// config.header['access_token'] = uni.getStorageSync('access_token')
		case 202:
			return response.data
			break
		case 203:
			break
		case 10001:
		case 1004:
			uni.removeStorageSync('access_token')
			// uni.showToast({
			// 	icon: 'none',
			// 	title: '用户凭证过期请重新登录！'
			// });
			uni.switchTab({ url: '/pages/Tabbar/Mine/Mine' })
			break
		case 400:

			return Promise.reject(response.data.msg)
			break
		case 404:

			return Promise.reject(response.data.msg)
		case 500:

			return Promise.reject(response.data.msg)
		default:
			uni.showToast({
				icon: 'none',
				title: response.data.msg
			})
			return response.data
	}
}, error => {
	console.log(error)
	//console.log('http requset error:',JSON.stringify(JSON.parse(error)))
	//监听401状态，则是401跳到登录
	if (error.statusCode == 401 || error.data.code == 401) {
		uni.reLaunch({
			url: '/pages/index/index.vue',
			fail(e) {
				console.log(e)
			}
		})
	}
	return Promise.reject(error)
})

export {
	http,
	baseUrl,
}